# -*- coding: utf-8 -*-
"""
Created on Thu Apr 27 09:09:04 2023

@author: suba
"""

# -*- coding: utf-8 -*-
"""
Created on Wed Mar 15 22:12:15 2023

@author: suba
"""

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
#导入数据集
df= pd.read_csv('E:/PROJECT_Dynasty2023/project_-dynasty2023/Project_MachineLearning/titanic_dataset.csv')
df = df.dropna(subset=['Embarked'])
df = df[['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']]
df['Sex'] = df['Sex'].map({'male': 0, 'female': 1})
df['Embarked'] = df['Embarked'].map({'S': 0, 'C': 1, 'Q': 2})
df = df.dropna()
X = df.iloc[:, 1:]
y = df.iloc[:, 0]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=50)
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
param_grid = {'min_samples_split':np.arange(2, 10),'max_depth':np.arange(2, 10)}
clf = DecisionTreeClassifier(splitter='best',random_state=50)
GS = GridSearchCV(clf, param_grid, cv=10)
GS.fit(X, y)
print(GS.best_params_)
print(GS.best_score_)
clf = DecisionTreeClassifier(max_depth=GS.best_params_['max_depth'],
                            min_samples_split=GS.best_params_['min_samples_split']
                            ,random_state=50)

clf.fit(X, y)
y_score=clf.score(X_test,y_test)
from sklearn.tree import plot_tree
plot_tree(clf, 
          feature_names = df.columns, 
          class_names = ['0','1'],  
          filled = True, 
          rounded = True,fontsize=6)

plt.savefig('tree_visualization.png') 